package com.lyc.project.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyc.common.model.entity.InterfaceInfo;
import com.lyc.common.model.entity.UserInterfaceInfo;
import com.lyc.project.common.ErrorCode;
import com.lyc.project.exception.BusinessException;
import com.lyc.project.mapper.InterfaceInfoMapper;
import com.lyc.project.service.InterfaceInfoService;
import com.lyc.project.service.UserInterfaceInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class InterfaceInfoServiceImpl extends ServiceImpl<InterfaceInfoMapper, InterfaceInfo>
    implements InterfaceInfoService {

    @Override
    public void validInterfaceInfo(InterfaceInfo interfaceInfo, boolean add) {
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String name = interfaceInfo.getName();
        // 创建时，所有参数必须非空
        if (add) {
            if (StringUtils.isAnyBlank(name)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
        }
        if (StringUtils.isNotBlank(name) && name.length() > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "名称过长");
        }

    }

    @Override
    public boolean removeByIdsTranslator(List<Long> ids) {
        for (Long id : ids) {
            InterfaceInfoService proxy = (InterfaceInfoService) AopContext.currentProxy();
            proxy.removeByIdTranslator(id);
        }
        return true;
    }

    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;

    @Override
    @Transactional  //当前方法添加了事务管理
    public boolean removeByIdTranslator(long id) {
        // 查询和接口名一样的用户接口关系表
        List<Long> userInterfaceInfoIdList = userInterfaceInfoService.lambdaQuery()
                .eq(UserInterfaceInfo::getInterfaceInfoId, id).list()
                .stream().map(UserInterfaceInfo::getId).collect(Collectors.toList());
        boolean b = this.removeById(id);
        if(b){
            return userInterfaceInfoService.removeBatchByIds(userInterfaceInfoIdList);
        }
        return false;
    }
}




